package mac5855.app.controllers;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mac5855.app.dao.CategoriaDAO;
import mac5855.app.dao.DAOFactory;
import mac5855.app.models.Categoria;

/**
 * Servlet implementation class Controller
 */
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Controller() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if(request.getRequestURI().endsWith("cadastra_pergunta")) {
			CategoriaDAO categoriaDAO = DAOFactory.getDAOFactory(1).getCategoriaDAO();
			Categoria[] categorias = categoriaDAO.findAll();
			request.setAttribute("categorias", categorias);
			RequestDispatcher rd = request.getRequestDispatcher("/restricted/cadastra_pergunta.jsp");
			rd.forward(request, response);
			return;
		}
		
		String business = request.getParameter("business");
		
		
		
		String className = "mac5855.app.controllers." + business;
		Class clazz;
		try {
		    clazz = Class.forName(className);
		} catch (ClassNotFoundException e) {
		    throw new ServletException("Não encontro a classe " + className);
		}
		
		BusinessLogic businessLogic;
		if (!BusinessLogic.class.isAssignableFrom(clazz)) {
		    throw new ServletException("classe não implementa a interface: " + className);
		}

		try {
		    businessLogic = (BusinessLogic) clazz.newInstance();
		} catch (InstantiationException e) {
		    throw new ServletException(e);
		} catch (IllegalAccessException e) {
		    throw new ServletException(e);
		}

		
		try {
		    businessLogic.execute(request, response);
		} catch (Exception e) {
		    throw new ServletException("A lógica de negócios causou uma exceção", e);
		}


	}

}
